﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Dapper;
using Dapper.Extensions;
using DapperDemo.Component.Model;


namespace DapperDemo.Api.Controllers
{
    //[Authorize]
    [AllowAnonymous]
    public class ValuesController : ApiController
    {
        
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        public ResultData<DapperTest> GetSingle()
        {
            var result = ResultData<DapperTest>.Error();
            var oInfo=conn.QueryFirstOrDefault<DapperTest>("select top 1 * from DapperTest");
            result = result.Success(oInfo);
            return result;
        }
        public ResultData<List<DapperTest>> GetList()
        {
            var result = ResultData<List<DapperTest>>.Error();
            var list = conn.Query<DapperTest>("select  * from DapperTest").ToList();
            result = result.Success(list);
            return result;
        }

        public ResultData Add()
        {
            var result = ResultData.Error(400,"");
            var oInfo = new DapperTest()
            {
                UserName = "test" + DateTime.Now.ToString("yyyyMMddHHmmssss"),
                CreatedDate = DateTime.Now
            };
            if (conn.Insert(oInfo)>0)
            {
                result=ResultData.Success();
            };
            
            return result;
        }
        public ResultData Update(int id)
        {
            var result = ResultData.Error(400, "");
            var oInfo = conn.QueryFirstOrDefault<DapperTest>($"select top 1 * from DapperTest Where UserId={id}");
            if (oInfo!=null)
            {
                oInfo.UpdatedDate = DateTime.Now;
                oInfo.TestDate1=DateTime.Now;
                oInfo.TestDate2=DateTime.Now;
                if (conn.Update(oInfo))
                {
                    result=ResultData.Success();
                }
            };

            return result;
        }
    }
}
